package com.seo.controller.keyWord;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.seo.function.PageTool;
import com.seo.pojo.ReturnBody;
import com.seo.service.keyword.sdk.KeywordGService;
import com.seo.service.keyword.sdk.KeywordService;
import com.seo.service.keyword.sdk.NewStationService;
import com.seo.service.sysUser.sdk.SysUserService;
import com.seo.utils.ClientConst;
import com.seo.utils.DateUtil;
import com.seo.utils.Jurisdiction;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: 关键词新站Controller
 * @author rtc
 * @version 2019.10.18 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "newStation/")
public class NewStationController {

	@Resource(name = "newStationService")
	private NewStationService newStationService;
	
	@Autowired
	private KeywordGService keywordGService;
	
	@Autowired
	private PageTool pageTool;
	
	@Resource(name = "keywordService")
	private KeywordService keywordService;
	
	@Autowired
	private SysUserService sysUserService;

	/**
	 * 新站网站列表
	 * @param param param
	 * @param request request
	 * @return String
	 */
	@RequestMapping(value = "/list")
	public String list(@RequestParam Map<String, Object> param, HttpServletRequest request) {
		log.info("进入新站网站列表...");
		List<Map<String, Object>> venderList = keywordGService.getVenderList(); //厂商列表
		param.put("userType", "admin");
		Integer id = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		Map<String, Object> sysUser = sysUserService.getSysUserById(id);
		String dataAuthority = (String)sysUser.get("dataAuthority");
		if("00".equals(dataAuthority)) {
			param.put("belongId", id);
		}
		
		PageInfo<?> page = pageTool.getAutoPage(newStationService::getNewDomainList, param);
		request.setAttribute("page", page);
		request.setAttribute("param", param);
		request.setAttribute("venderList", venderList);
		return "newStation/new_station_list";
	}
	
	/**
	 * 跳转网站新增
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "domain/toAdd")
	public String toKeyWordAdd(HttpServletRequest request) throws Exception {
		log.info("【跳转网站新增】---【开始】---");
		List<Map<String, Object>> venderList = keywordGService.getVenderList(); //厂商列表
		request.setAttribute("venderList", venderList);
		request.setAttribute("msg", "saveNewKeywordsDomain");
		log.info("【跳转网站新增】---【结束】---");
		return "newStation/new_station_add";
	}
	
	/**
	 * 新增新站网站
	 * @param params params
	 * @return ReturnBody
	 */
	@RequestMapping("/saveNewKeywordsDomain")
	public String saveNewKeywordsDomain(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("【新增新站网站】---【开始】---");
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		params.put("create_id", user.get("id"));
		ReturnBody rb = ReturnBody.init();
		try {
			rb =  newStationService.saveNewKeywordsDomain(params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("【新增新站网站】---【结束】---");
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
	/**
	 * 跳转网站编辑
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "domain/toEdit")
	public String toEdit(@RequestParam Map<String, Object> params, HttpServletRequest request) throws Exception {
		log.info("【跳转网站编辑】---【开始】---");
		List<Map<String, Object>> venderList = keywordGService.getVenderList(); //厂商列表
		params.put("userType", "admin");
		List<Map<String, Object>> newDomainList = newStationService.getNewDomainList(params);
		if(newDomainList != null) {
			request.setAttribute("info", newDomainList.get(0));
		}
		request.setAttribute("venderList", venderList);
		request.setAttribute("msg", "updateNewKeywordsDomain");
		log.info("【跳转网站编辑】---【结束】---");
		return "newStation/new_station_add";
	}
	
	/**
	 * 编辑新站网站
	 * @param params params
	 * @return ReturnBody
	 */
	@RequestMapping("/updateNewKeywordsDomain")
	public String updateNewKeywordsDomain(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("【编辑新站网站】---【开始】---");
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		params.put("update_id", user.get("id"));
		ReturnBody rb = ReturnBody.init();
		try {
			rb =  newStationService.updateNewKeywordsDomain(params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("【编辑新站网站】---【结束】---");
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
	/**
	 * 修改网站状态
	 * @param param param
	 * @param request request
	 * @return ReturnBody
	 */
	@RequestMapping(value = "/updateDomainState")
	@ResponseBody
	public ReturnBody updateDomainState(@RequestParam Map<String, Object> param, HttpServletRequest request) {
		log.info("修改网站状态开始...");
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		if(param == null || param.size() == 0) {
			rb.error("缺少参数");
		}
		param.put("update_id", user.get("id"));
		rb = newStationService.updateDomainState(param);
		log.info("修改网站状态结束...");
		return rb;
	}
	
	/**
	 * 跳转新增网站关键词页面
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "domain/toKeywordsAdd")
	public String toKeywordsAdd(@RequestParam Map<String, Object> params, HttpServletRequest request) throws Exception {
		log.info("【跳转新增网站关键词页面】---【开始】---");
		List<Map<String, Object>> engine = keywordService.getEngineList();
		request.setAttribute("engine", engine);
		request.setAttribute("params", params);
		log.info("【跳转新增网站关键词页面】---【结束】---");
		return "newStation/domain_keyWord_add";
	}
	
	/**
	 * 网站关键词新增
	 * @param param  param
	 * @return ReturnBody
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "domain/add")
	@ResponseBody
	public ReturnBody add(@RequestParam Map<String, Object> param) throws Exception {
		log.info("【网站关键词新增】---【开始】---");
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		try {
			if (param == null || param.isEmpty() || user == null || user.isEmpty()) {
				return rb.error("参数不能为空");
			}
			if (!param.containsKey("engineCode")) {
				return rb.error("请选择搜索引擎");
			}
			param.put("createId", user.get("id"));
			rb.run(newStationService.saveDomainKeyWordToAdmin(param, "02"));
			log.info("【admin关键词新增】---【结束】---");
		} catch (Exception e) {
			log.error("网站关键词新增异常[{}]", e);
			return rb.error();
		}
		return rb;
	}
	
	@RequestMapping("/keyWordlist")
	public String keyWordlist(@RequestParam Map<String, Object> pam,HttpServletRequest request, HttpSession session) {
		log.info("进入新站关键字列表...");
		List<Map<String, Object>> venderList = newStationService.getVenderList(); //厂商列表
		List<Map<String, Object>> engineList = newStationService.getEngineList(); //搜索引擎列表
		List<Map<String, Object>> groupList = null;
		String userId = (String) pam.get("userId");
		if(StringUtils.isNotBlank(userId)){
			groupList = newStationService.getGroupByUserId(Integer.parseInt(userId));
		}
		//排名情况
		String ranking = (String) pam.get("ranking");
		if(StringUtils.isNotBlank(ranking)){
			String rankingStr = ranking.substring(0, ranking.indexOf("-"));
			String rankingState = ranking.substring(ranking.indexOf("-")+1);
			pam.put("rankingStr", Integer.valueOf(rankingStr));
			pam.put("rankingState", rankingState);
			pam.put("currentTime", DateUtil.getDay());
		}
		//排名区间 1：1-10 2：11-50 3： 51-100 4: 100+
		String rankingInterval = (String) pam.get("rankingInterval");
		if(StringUtils.isNotBlank(rankingInterval)) {
			String startRanking = null;
			String endRanking = null;
			if("1".equals(rankingInterval)) {
				startRanking = "1";
				endRanking = "10";
			}else if("2".equals(rankingInterval)) {
				startRanking = "11";
				endRanking = "50";
			}else if("3".equals(rankingInterval)) {
				startRanking = "51";
				endRanking = "100";
			}else {
				startRanking = "100";
			}
			pam.put("startRanking", startRanking);
			pam.put("endRanking", endRanking);
		}
		
		Integer id = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		Map<String, Object> sysUser = sysUserService.getSysUserById(id);
		String dataAuthority = (String)sysUser.get("dataAuthority");
		if("00".equals(dataAuthority)) {
			pam.put("belongId", id);
		}
		
		PageInfo<?> page = pageTool.getAutoPage(newStationService::getKeyWordsList,pam);
		request.setAttribute("page", page);
		request.setAttribute("venderList", venderList);
		request.setAttribute("engineList", engineList);
		request.setAttribute("pam", pam);
		request.setAttribute("groupList", groupList);
		return "newStation/keyWord_list";

	}
	/**
	 * 进入批量价格修改页面
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping("/editPriceP")
	public String editPriceP(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入价格和类型页面");
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("price", pam.get("price"));
		request.setAttribute("action", "editPrice");
		return "newStation/price";
	}

	/**
	 * 进入价格和类型修改页面
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping("/editPricePage")
	public String editPricePage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入价格和类型页面");
		request.setAttribute("targetRanking", pam.get("targetRanking"));
		request.setAttribute("price", pam.get("price"));
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("action", "editPrice");
		return "newStation/price_edit";
	}
	
	@RequestMapping("/editPrice")
	public String editPrice(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改价格和类型");
		ReturnBody rb = ReturnBody.init();
		rb = newStationService.updatePriceAndTargetRanking(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
	/**
	 * 批量删除 和 单独删除
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(@RequestParam Map<String, Object> pam, HttpSession session) {
		log.info("进入关键词删除方法...");
		String msg = "";
		try {
			newStationService.deleteArr(pam);
			msg = "true";
		} catch (Exception e) {
			msg = "error";
		}
		
		return msg;

	}

	/**
	 * 启用停用
	 * @param pam
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/keyWordEnable")
	@ResponseBody
	public String keyWordEnable(@RequestParam Map<String, Object> pam, HttpSession session) {
		log.info("进入关键词启用停用方法...");
		String msg = "";// 01 成功    02 失败   03 您的关键词最少要使用15天    04 您的关键词最少要达标30天
		String oldState = (String) pam.get("oldState"); // 原来的状态
		String newState = (String) pam.get("newState"); // 现有的状态 也就是所要修改的状态
		String id = (String) pam.get("ids");//关键词主键
		Map<String, Object> p = new HashMap<>();
		p.put("id", id);
		Map<String, Object> keyword = newStationService.getInfoBykeywordId(p);
		int reachDays = (int) keyword.get("reach_days");//达标天数
		String createTime = (String) keyword.get("create_time");//时间
		if(reachDays == 0) {
			Long dayNum = DateUtil.getDaySub(createTime, DateUtil.getTime());
			if(dayNum>15) {
				if("01".equals(newState)){ // 如果现有状态 为01 使用中  那么原来的状态 必须为02 已停用
					if("02".equals(oldState)){
						pam.put("state", newState);
						try {
							newStationService.updatekeyWordReviewDisabled(pam);
							msg = "01";
						} catch (Exception e) {
							msg = "02";
						}
					}
				}else if("02".equals(newState)){ // 如果现有状态 为02 已停用  那么原来的状态 必须为01  使用中
					if("01".equals(oldState)){
						pam.put("state", newState);
						try {
							newStationService.updatekeyWordReviewDisabled(pam);
							msg = "01";
						} catch (Exception e) {
							msg = "01";
						}
					}
				}
			}else {
				msg = "03";
			}
		}else {
				if(reachDays>30) {
					if("01".equals(newState)){ // 如果现有状态 为01 使用中  那么原来的状态 必须为02 已停用
						if("02".equals(oldState)){
							pam.put("state", newState);
							try {
								newStationService.updatekeyWordReviewDisabled(pam);
								msg = "01";
							} catch (Exception e) {
								msg = "02";
							}
						}
					}else if("02".equals(newState)){ // 如果现有状态 为02 已停用  那么原来的状态 必须为01  使用中
						if("01".equals(oldState)){
							pam.put("state", newState);
							try {
								newStationService.updatekeyWordReviewDisabled(pam);
								msg = "01";
							} catch (Exception e) {
								msg = "02";
							}
						}
					}
				}else {
					msg = "04";
				}
		}
		return msg;
	}
	
	/**
	 * 进入修改厂商页面
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入编辑用户页面");
		List<Map<String, Object>> venderList = keywordGService.getVenderList();
		request.setAttribute("venderList", venderList);
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("action", "editvender");
		return "newStation/vender_edit";
	}
	
	@RequestMapping("/editvender")
	public String editvender(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改厂商");
		ReturnBody rb = ReturnBody.init();
		rb = newStationService.updateVender(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}

	/**
	 * 导出
	 * @param pam
	 * @param response
	 */
	@RequestMapping("export")
	public void exportKeyWord(@RequestParam Map<String, Object> pam,HttpServletResponse response){
		XSSFWorkbook workbook = new XSSFWorkbook();
		try {
			workbook = newStationService.exportKeyWord(pam, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 导入
	 * @param file
	 * @return
	 */
	@RequestMapping("upload")
	public String importKeyWord(@RequestParam("file") MultipartFile file,@RequestParam Map<String, Object> pam,HttpServletRequest request){
		long a = System.currentTimeMillis();
		ReturnBody result = ReturnBody.init();
		String fileName = file.getOriginalFilename();
		String importTime = (String) pam.get("importTime");
		try {
			result.run(newStationService.importKeyWord(fileName, file, importTime));
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("result", result);
		log.info("\r<br>执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");
		return "newStation/keyWord_import";
	}
	
	/**
	 * 进入最初排名修改页面
	 * @param pam
	 * @param request
	 * @return
	 */
	@RequestMapping("/editInitRankingPage")
	public String editInitRankingPage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入最初排名页面");
		request.setAttribute("initRanking", pam.get("initRanking"));
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("action", "editInitRanking");
		return "newStation/initRanking_edit";
	}
	/**
	 * 修改最初排名
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping("/editInitRanking")
	public String editInitRanking(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改最初排名");
		ReturnBody rb = ReturnBody.init();
		rb = newStationService.updatePriceAndTargetRanking(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}

	/**
	 * 进入昨日排名修改页面
	 * @param pam
	 * @param request
	 * @return
	 */
	@RequestMapping("/editYesRankingPage")
	public String editYesRankingPage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入昨日排名页面");
		request.setAttribute("newRanking", pam.get("newRanking"));
		request.setAttribute("name", pam.get("name"));
		request.setAttribute("engine_code", pam.get("engine_code"));
		request.setAttribute("domain", pam.get("domain"));
		request.setAttribute("run_time", pam.get("run_time"));
		request.setAttribute("action", "editYesRanking");
		return "newStation/yesRanking_edit";
	}
	/**
	 * 修改昨日排名
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping("/editYesRanking")
	public String editYesRanking(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改昨日排名");
		ReturnBody rb = ReturnBody.init();
		rb = newStationService.updateYesRanking(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}

	/**
	 * 进入最新排名修改页面
	 * @param pam
	 * @param request
	 * @return
	 */
	@RequestMapping("/editNewRankingPage")
	public String editNewRankingPage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入最新排名页面");
		request.setAttribute("newRanking", pam.get("newRanking"));
		request.setAttribute("name", pam.get("name"));
		request.setAttribute("engine_code", pam.get("engine_code"));
		request.setAttribute("domain", pam.get("domain"));
		request.setAttribute("action", "editNewRanking");
		return "newStation/newRanking_edit";
	}
	/**
	 * 修改最新排名
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping("/editNewRanking")
	public String editNewRanking(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改最新排名");
		ReturnBody rb = ReturnBody.init();
		rb = newStationService.updateNewRanking(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}

	/**
	 * 回收站
	 * @param param 关键词
	 * @return Map<String,Object>
	 */
	@RequestMapping(value = "/recycleBin")
	public ModelAndView recycleBin(@RequestParam Map<String, Object> param, HttpServletRequest request) throws Exception {
		log.info("【获取回收站数据】---【开始】--param={}", param);
		ModelAndView mv = new ModelAndView();
		PageInfo<?> page = pageTool.getAutoPage(newStationService::getRecycleBinList, param);
		request.setAttribute("page", page);
		request.setAttribute("param", param);
		mv.setViewName("newStation/keyWord_recycleBin");
		log.info("【获取回收站数据】---【结束】---");
		return mv;
	}
	
	/**
	 * 导出回收站列表
	 * @param pam
	 * @param response
	 */
	@RequestMapping("exportRecycleBin")
	public void exportKeyWordRecycleBin(@RequestParam Map<String, Object> pam, HttpServletResponse response){
		XSSFWorkbook workbook = new XSSFWorkbook();
		try {
			XSSFSheet sheet = workbook.createSheet("信息表");
			List<Map<String, Object>> export = newStationService.getRecycleBinList(pam); // 导出数据
			String fileName = "新站关键词回收站列表-" + DateUtil.getDay() + ".xlsx";// 设置要导出的文件的名字
			// 新增数据行，并且设置单元格数据

			int rowNum = 1;
			String[] headers = { "ID", "用户名", "关键词", "域名", "引擎", "指数","单价 (元)","修改时间" };
			// headers表示excel表中第一行的表头

			XSSFRow row = sheet.createRow(0);
			// 在excel表中添加表头

			for (int i = 0; i < headers.length; i++) {
				XSSFCell cell = row.createCell(i);
				XSSFRichTextString text = new XSSFRichTextString(headers[i]);
				cell.setCellValue(text);
			}
			Map<String, Object> exportMap = null;
			// 在表中存放查询到的数据放入对应的列
			for (int i = 0; i < export.size(); i++) {
				XSSFRow row1 = sheet.createRow(rowNum);
				exportMap = export.get(i);
				String engineCode = (String) exportMap.get("engine_code");
				if("01".equals(engineCode)) {
					engineCode= "百度PC";
				} else if("02".equals(engineCode)) {
					engineCode= "百度移动";
				} else if("03".equals(engineCode)) {
					engineCode= "360PC";
				} else if("04".equals(engineCode)) {
					engineCode= "360移动";
				} else if("05".equals(engineCode)) {
					engineCode= "神马";
				} else if("06".equals(engineCode)) {
					engineCode= "搜狗pc";
				} else if("07".equals(engineCode)) {
					engineCode= "搜狗移动";
				}
				String keyword_index = (String) exportMap.get("keyword_index");
				
				if("-1".equals(keyword_index)) {
					keyword_index = "0";
				}
			
				row1.createCell(0).setCellValue(exportMap.get("id").toString());
				row1.createCell(1).setCellValue(exportMap.get("userName").toString());
				row1.createCell(2).setCellValue(exportMap.get("name").toString());
				row1.createCell(3).setCellValue(exportMap.get("domain").toString());
				row1.createCell(4).setCellValue(engineCode);
				row1.createCell(5).setCellValue(keyword_index);
				row1.createCell(6).setCellValue(exportMap.get("price").toString());
				row1.createCell(7).setCellValue(exportMap.get("update_time").toString());
				rowNum++;
			}
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition",
					"attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
			response.flushBuffer();
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/keyWordUpdate")
	@ResponseBody
	public String keyWordUpdate(@RequestParam Map<String, Object> pam) {
		log.info("进入恢复关键词方法...");
		String msg = "";
		try {
			newStationService.keyWordUpdate(pam);
			msg = "true";
		} catch (Exception e) {
			msg = "error";
		}
		
		return msg;
	}
	
	@RequestMapping("/deleteK")
	@ResponseBody
	public String deleteK(@RequestParam Map<String, Object> pam) {
		log.info("进入删除关键词方法...");
		String msg = "";
		try {
			newStationService.deleteK(pam);
			msg = "true";
		} catch (Exception e) {
			msg = "error";
		}
		
		return msg;
	}

}
